﻿using System;
using System.ServiceModel;
using System.Threading;
using log4net;

namespace FlightSearchServer
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main Thread";

            if (args.Length != 3)
            {
                Console.WriteLine("Usage: {0} <clients port> <sellers port> <log file>", AppDomain.CurrentDomain.FriendlyName);
                return;
            }

            GlobalContext.Properties["LogFileName"] = args[2];

            var log = LogManager.GetLogger(typeof(Program));

            if (log.IsInfoEnabled)
            {
                log.Info("Starting...");
            }

            var searchServiceUri = "http://localhost:" + args[0] + "/Services/FlightsSearch";
            var regServiceUri = "http://localhost:" + args[1] + "/Services/AlliancesRegistartion";

            var searchManager = new SearchManager();

            try
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("Starting registration service on " + regServiceUri);
                }

                var rs = new RegistartionService(searchManager);
                var sellerRegistration = new ServiceHost(rs, new Uri(regServiceUri));
                sellerRegistration.Open();

                if (log.IsDebugEnabled)
                {
                    log.Info("... OK");
                }
            }
            catch (Exception e)
            {
                if (log.IsFatalEnabled)
                {
                    log.Fatal("... Failed", e);
                }

                return;
            }

            try
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("Starting flight search service on " + searchServiceUri);
                }

                var ss = new SearchService(searchManager);
                var flightSearch = new ServiceHost(ss, new Uri(searchServiceUri));
                flightSearch.Open();

                if (log.IsDebugEnabled)
                {
                    log.Info("... OK");
                }
            }
            catch (Exception e)
            {
                if (log.IsFatalEnabled)
                {
                    log.Fatal("... Failed", e);
                }

                return;
            }

            if (log.IsInfoEnabled)
            {
                log.Info("Running...");
            }

            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();

            log.Debug("Stopping...");
        }
    }
}
